package com.liuzy.family.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liuzy.family.entity.CalendarEntity;
import com.liuzy.family.mapper.CalendarEntityMapper;
import com.liuzy.family.util.DateKit;

@Controller
@RequestMapping(value = "/calendar", method = RequestMethod.POST)
public class CalendarController extends BaseController {

	private static volatile CalendarEntity todayEntity = null;//记住今天的日期对象
	private static volatile Map<String, Long> daysMap = new HashMap<>();//记住已计算过的下一生日

	@Autowired
	private CalendarEntityMapper calendarEntityMapper;

	@RequestMapping("/byYang")
	@ResponseBody
	public Object yl(String date) {
		if (date == null) {
			return render(render("error"));
		}
		return render(render(calendarEntityMapper.getByYang(date)));
	}
	
	@RequestMapping("/byNong")
	@ResponseBody
	public Object nl(String date) {
		if (date == null) {
			return render("error");
		}
		return render(calendarEntityMapper.getByNong(date));
	}
	
	@RequestMapping("/next")
	@ResponseBody
	public Object nextBirthday(String nong) {//传入农历：-2-26 (前面带杠)
		if (nong == null) {
			return render("error");
		}
		Long days;
		if (todayEntity == null || !todayEntity.getYang().equals(DateKit.format(new Date()).replace("-0", "-"))) {
			todayEntity = calendarEntityMapper.today();
			daysMap.clear();
		} else {//如果已经计算过
			days = daysMap.get(nong);
			if (days != null) {
				return render(days);
			}
		}
		if (todayEntity.getNong().endsWith(nong)) {//如果就是今天
			days = new Long(0);
		} else {
			days = getDays(nong);
		}
		daysMap.put(nong, days);
		return render(days);
	}

	public Long getDays(String nong) {
		Map<String, Object> params = new HashMap<>();
		params.put("nong", nong);
		params.put("todayId", todayEntity.getId());
		CalendarEntity nextDay = calendarEntityMapper.nextNongDay(params);
		Date endDate = DateKit.parse(nextDay.getYang());
		return (endDate.getTime() - new Date().getTime()) / (24 * 60 * 60 * 1000) + 1;
	}
	
}
